//index.js
import * as echarts from '../../components/ec-canvas/echarts'

const app = getApp()
const { formatTime} = require('../../utils/util')
const jobMixin = require('../../utils/mixins/job')
const navMixin = require('../../utils/mixins/nav')
const {tabItems} = require('./data/tab')
const process = require('./data/process')
const undoneDate = require('data/undone')
const chartOption = require('./charts/chart')
const { workList, setWork, dayList, undone, check, checkTb, monthComplete, dayUndone, monthUndoneDate, undoneTb, weeksTable, weeksUndone, outLogin } = require('../../utils/request/api')
const inputMixin = require('../../utils/mixins/input')

let date = formatTime(new Date())

function initChart(option){
  return function (cvs, width, height){
    let chart = echarts.init(cvs, null, { width, height })

    cvs.setChart(chart)
    chart.setOption(option)

    return chart
  }
}

Page({
  data: {
    // 通用
    album: [], // 相册
    tabItems, // TAB选项
    tabIndex: 0, // TAB索引
    isSubmit:false, //是否提交，提交后不可再操作

    // 粗加工
    processTable: '', // 粗加工情况日志记录详情表
    processWeekCompletion: '', // 周工作完成情况可视化
    processWeekCompletionDate: date, // 对应时间
    processMonthCompletion: '', // 月工作完成情况可视化
    processMonthCompletionDate: date.slice(0, -3), // 对应时间
    processMonthCompletionDateYc: date.slice(0, -3),
    processDayAbnormal: '', // 日异常情况占比
    processDayAbnormalDate: date, // 对应时间
    processWeekAbnormal: '', // 周异常情况占比
    processWeekAbnormalDate: date, // 对应时间
    processMonthAbnormal: '', // 月日常情况占比
    processMonthAbnormalDate: date.slice(0, -3), // 对应时间

    //周数据
    roughWeekPicker: date,  //粗加工周工作完成情况可视化星期日期
    roughWeekPickerDate: [], //粗加工周工作完成情况可视化数据
    roughWeekYcPicker: date,  //粗加工周异常情况占比日期
    roughWeekYcPickerDate: [],  //粗加工周异常情况占比数据

    line1: chartOption.line1,  //粗加工检查执行工作完成时间折线图
    line1: chartOption.line2,  //餐具消毒检查执行工作完成时间折线图
    circle1: chartOption.circle1, //月完成工作情况可视化饼图
    circle2: chartOption.circle2, //日异常情况占比饼图
    circle3: chartOption.circle3,  //周异常情况占比饼图
    circle4: chartOption.circle4, //月异常情况占比饼图

    ecLine1: { //粗加工检查执行工作完成时间
      onInit: initChart(chartOption.line1),
    },
    ecLine2: {  //餐具消毒检查执行工作完成时间
      onInit: initChart(chartOption.line2),
    },
    ecCircle1: {  //月完成工作情况可视化
      onInit: initChart(chartOption.circle1, 'pie'),
    },
    ecCircle2: {   //日异常情况占比
      onInit: initChart(chartOption.circle2, 'pie'),
    },
    ecCircle3: {  //周异常情况占比
      onInit: initChart(chartOption.circle3, 'pie'),
    },
    ecCircle4: {  //月异常情况占比
      onInit: initChart(chartOption.circle4, 'pie'),
    },

    // 检查未完成情况详情
    undoneJob:[],
    monthUndone: undoneDate.monthUndone,  //月工作完成情况可视化
    dayUndoneDate: undoneDate.dayUndone,  //日异常情况占比
    monthAbnormal: undoneDate.monthAbnormal,  //月异常情况占比

    // 餐具消毒
    desinfectTime: '', // 检查工作完成时间
    tableUndoneDate:{}, //消毒未完成情况详情
    processTableware: process.tableware,  //餐具消毒日志记录详情表
    disinfectionPicker:date, //餐具消毒周工作完成情况可视化时间选择
    disinfectionPickerData:'', //周工作完成情况可视化数据

    

    // 工作人员
    isEnter: app.globalData.isEnter,
    job: '', // 岗位
    processEditTable: process.data.map(item => Object.assign({}, item, { list: item.list.map(item => Object.assign({}, item, { checked: false })) })), // 粗加工情况日记录详情登记表,false
    processCheckTime: '', // 对应时间
    desinfectEditTable: '', // 餐具消毒记录详情登记表
    desinfectCheckTime: '', // 对应时间
  },
  onLoad(){
    this.getmsgStorage();  //记录是否有登录
    this.getRoughMachining();  //进入页面的粗加工列表展示
    this.checkTime();  //粗加工检查工作完成时间
    this.undone();  //粗加工未完成情况详情
  },
  
  onShow(option){
      this.getMonthDate();  //月工作完成情况可视化
      this.getDayUndone();  //日异常情况占比
      this.getMonthAbnormal(); //月异常情况占比
      this.getTableUndone();  //餐具消毒为完成情况详情
      this.getWeeksTable();  //粗加工周工作完成情况可视化
      this.getWeekYcDate();  //粗加工周工作异常完成情况占比
      this.getdisinfection();  //餐具消毒周工作完成情况可视化
      this.checkTbTime();  //餐具消毒记录

    
  },

  //获取是否登录的storage
  getmsgStorage(){
    let {isEnter} = this.data;
    //获取storage
    isEnter = wx.getStorageSync('dataMsg')

    if (isEnter) {
      this.setData({ isEnter })
    }
  },

  // 退出
  exitLogin(){
    wx.clearStorage();
    wx.request({
      url: outLogin,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      success:(res) => {
        console.log(res);
      }
    })
    wx.navigateTo({
      url: '../login/login',
    })
  },

  //粗加工情况检查工作完成时间
  checkTime(){
    wx.request({
      url: check,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      success: (res) => {
        let { code, data, mes } = res.data;
        for (var i = 0; i < chartOption.line1.series[0].data.length;i++){
          chartOption.line1.series[0].data[i] = parseInt(mes[i].audit_time.substring(0, 2).replace(/\b(0)/, "")) + parseFloat(mes[i].audit_time.substring(3,5).replace(/\b(0)/,"") / 60 );
        }

        for (var i = 0; i < chartOption.line1.series[1].data.length; i++) {
          chartOption.line1.series[1].data[i] = parseInt(mes[i].check_time.substring(0, 2).replace(/\b(0)/, "")) + parseFloat(mes[i].check_time.substring(3, 5).replace(/\b(0)/, "") / 60);
        }

        this.setData({
          ecLine1: { //粗加工检查执行工作完成时间
            onInit: initChart(chartOption.line1),
          },
        })
        
      }
    })
  },

  //餐具消毒记录情况检查工作完成时间
  checkTbTime() {
    wx.request({
      url: checkTb,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      success: (res) => {
        let { code, data, mes } = res.data;
        if(code == 200){
          for (var i = 0; i < chartOption.line2.series[0].data.length; i++) {
            chartOption.line2.series[0].data[i] = parseInt(mes[i].audit_time.substring(0, 2).replace(/\b(0)/, "")) + parseFloat(mes[i].audit_time.substring(3, 5).replace(/\b(0)/, "") / 60);
          }

          for (var i = 0; i < chartOption.line2.series[1].data.length; i++) {
            chartOption.line2.series[1].data[i] = parseInt(mes[i].check_time.substring(0, 2).replace(/\b(0)/, "")) + parseFloat(mes[i].check_time.substring(3, 5).replace(/\b(0)/, "") / 60);
          }

          this.setData({
            ecLine2: { //粗加工检查执行工作完成时间
              onInit: initChart(chartOption.line2),
            },
          })
        }
      }
    })
  },

  //餐具消毒周工作完成情况可视化日期改变请求数据
  binddisinfectionChange(e){
    this.setData({
      disinfectionPicker: e.detail.value
    })
    this.getdisinfection();
  },

  //餐具消毒周工作完成情况可视化
  getdisinfection() {
    let { disinfectionPickerData} = this.data;
    wx.request({
      url: weeksTable,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      data: { time: this.data.disinfectionPicker },
      success: (res) => {
        let { code, data, mes } = res.data;
        disinfectionPickerData = mes;
        for (var i = 0; i < disinfectionPickerData.length; i++) {
          disinfectionPickerData[i].spend = disinfectionPickerData[i].spend * 100;
        }
        this.setData({
          disinfectionPickerData
        })
      }
    })
  },

  //粗加工周工作完成情况可视化日期改变请求数据
  bindDateChange(e){
    this.setData({
      roughWeekPicker: e.detail.value
    })
    this.getWeeksTable();
  },

  //粗加工周工作完成情况可视化
  getWeeksTable() {
    let { roughWeekPickerDate} = this.data;
    wx.request({
      url: weeksTable,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      data: { time: this.data.roughWeekPickerDate },
      success: (res) => {
        let { code, data, mes } = res.data;
        roughWeekPickerDate = mes;
        for (var i = 0; i < roughWeekPickerDate.length; i++) {
          roughWeekPickerDate[i].spend = roughWeekPickerDate[i].spend * 100;
        }
        this.setData({
          roughWeekPickerDate
        })
      }
    })
  },

  //月工作完成情况可视化时间选择
  monthDateChange(e){
    this.setData({
      processMonthCompletionDate:e.detail.value
    })
    this.getMonthDate();
  },

  //月工作完成情况可视化
  getMonthDate() {
    let { monthUndone } = this.data;

    wx.request({
      url: monthComplete,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      data: { time: this.data.processMonthCompletionDate },
      success: (res) => {
        let { code, data, mes } = res.data;

        chartOption.circle1.title.text = parseInt(mes.complete * 100) + '%';
        chartOption.circle1.series[0].data[0].value = parseInt(mes.complete * 100);
        chartOption.circle1.series[0].data[1].value = parseInt(100 - mes.complete * 100);

        setTimeout(() => {
          this.setData({
            monthUndone: mes,
            ecCircle1: {  //月完成工作情况可视化
              onInit: initChart(chartOption.circle1, 'pie'),
            },
            
          })
        }, 3000)
      }
    })
  },

  //日异常情况占比
  dayDateChange(e){
    this.setData({
      processDayAbnormalDate: e.detail.value
    })
    this.getDayUndone();
  },

  //日异常情况占比
  getDayUndone() {
    wx.request({
      url: dayUndone,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      data: { time: this.data.processDayAbnormalDate },
      success: (res) => {
        let { code, data, mes } = res.data;

        chartOption.circle2.title.text = parseInt(mes.complete * 100) + '%';
        chartOption.circle2.series[0].data[0].value = parseInt(mes.complete * 100);
        chartOption.circle2.series[0].data[1].value = parseInt(100 - mes.complete * 100);

        this.setData({
          dayUndoneDate: mes,
          ecCircle2: {  //月完成工作情况可视化
            onInit: initChart(chartOption.circle2, 'pie'),
          },
        })
      }
    })
  },

  //粗加工周异常情况占比日期改变请求数据
  roughWeekChange(e) {
    this.setData({
      roughWeekYcPicker: e.detail.value
    })
    this.getWeekYcDate();
  },

  // 粗加工周异常情况占比数据
  getWeekYcDate() {
    let { roughWeekYcPickerDate } = this.data;
    wx.request({
      url: weeksUndone,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      data: { time: this.data.roughWeekYcPicker },
      success: (res) => {
        let { code, data, mes } = res.data;

        chartOption.circle3.title.text = parseInt(mes.complete * 100) + '%';
        chartOption.circle3.series[0].data[0].value = parseInt(mes.complete * 100);
        chartOption.circle3.series[0].data[1].value = parseInt(100 - mes.complete * 100);

        this.setData({
          roughWeekYcPickerDate: mes,
          ecCircle3: {  //月完成工作情况可视化
            onInit: initChart(chartOption.circle3, 'pie'),
          },
        })
      }
    })
  },

  //月异常情况占比
  monthYcDateChange(e){
    this.setData({
      processMonthCompletionDateYc: e.detail.value
    })
    this.getMonthAbnormal()();
  },

  //月异常情况占比
  getMonthAbnormal() {
    wx.request({
      url: monthUndoneDate,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      data: { time: this.data.processMonthCompletionDateYc },
      success: (res) => {
        let { code, data, mes } = res.data;

        chartOption.circle4.title.text = parseInt(mes.complete * 100) + '%';
        chartOption.circle4.series[0].data[0].value = parseInt(mes.complete * 100);
        chartOption.circle4.series[0].data[1].value = parseInt(100 - mes.complete * 100);

        this.setData({
          monthAbnormal: mes,
          ecCircle4: {  //月完成工作情况可视化
            onInit: initChart(chartOption.circle4, 'pie'),
          },
        })
      }
    })
  },

  //餐具消毒未完成情况
  getTableUndone(){
    let { tableUndoneDate} = this.data;
    wx.request({
      url: undoneTb,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      data: { time: this.data.processMonthAbnormalDate },
      success: (res) => {
        let { code, data, mes } = res.data;
        if(code == 200){
          tableUndoneDate = mes;

          for (var i = 0; i < tableUndoneDate.length; i++) {
            tableUndoneDate[i].name = tableUndoneDate[i].title;
          }
          this.setData({
            tableUndoneDate
          })
        }
      }
    })
  },

  //把chart.js中的需要变化的数据取出来
  getChartData(){
    return {
      linexAxis: chartOption.line1.xAxis.data,
      lineAudit: chartOption.line1.series[0].data,
      lineCheck: chartOption.line1.series[1].data
    }
  },

  //tab1粗加工情况--未完成情况详情
  undone(){
    wx.request({
      url: undone,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      success:(res) => {
        let {code,data,mes} = res.data;
        if(code == 200){
          this.setData({
            undoneJob: mes
          })
        }
      }
    })
  },

  //请求粗加工情况详情的api
  getRoughMachining(){
    let { processTable} = this.data;

    wx.request({
      url: dayList,
      method:'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
      success:(res) => {
        let {code,data,mes} = res.data
        if(code == 200){
          this.setData({
            processTable: mes.data
          })
        }else{
          wx.navigateTo({
            url: '../login/login',
          })
        }
      }
    })
  },

  /**
   * @desc 当tab切换时
   */
  onTabChange(e){
    let {currentTarget: {dataset: {index}}} = e
    let { job, isSubmit, processEditTable, processTableware, desinfectEditTable} = this.data;

    if(index == 2){ // 工作人员操作，需要用户登录
      wx.request({
        url: workList,
        method: 'POST',
        header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
        data: { isEnter: this.data.isEnter},
        success: (res) => {
          let {code,mes,url,data} = res.data;
          if(code == 200){
            this.setData({
              job:mes.jobsName,
              processEditTable:mes.data,
              processTableware:mes.tableWare
            }) 
          } 
          if ("isSubmit" in mes){
            this.setData({
              isSubmit: mes.isSubmit
            })
          }
        }
      })
    }

    this.setData({
      tabIndex: index,
    })
  },

  /**
   * @desc 选择时间
   */
  onDateTimeSelect(e){
    let {
      detail: value,
      currentTarget: {dataset: type}
    } = e

    this[`${type}Time`] = value
  },

  json2Form(json) {
    var str = [];
    for(var p in json) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
    }
    return str.join("&");
  },

  //更新粗加工操作列表的checked值
  onCustomeTap(e){
    let { processEditTable} = this.data;

    for (let i = 0; i < processEditTable.length;i++){
      for (let j = 0; j < processEditTable[i].list.length;j++){
        if (processEditTable[i].list[j].id == e.detail.id){
          processEditTable[i].list[j].checked = e.detail.checked;
          return;
        }
      }
    }
    let processEditTable2 = Object.assign({},processEditTable,processEditTable.map(item => Object.assign({}, item, { list: item.list.map(item => Object.assign({}, item, { checked})) })))
    this.setData({
      processEditTable: processEditTable2
    })
  },

  //更新消毒操作列表的checked值
  onCustomeTapdf(e) {
    let { processTableware } = this.data;

    for (let i = 0; i < processTableware.length; i++) {
        if (processTableware[i].id == e.detail.id) {
          processTableware[i].checked = e.detail.checked;
          return;
        }
    }

    let processTableware2 = Object.assign({}, processTableware, processTableware.map(item => Object.assign({}, item, { checked})));

    this.setData({
      processTableware: processTableware2
    })
  },

  //餐具消毒数量更新
  subNum(e){
    let { processTableware } = this.data;

    for (let i = 0; i < processTableware.length; i++) {
      if (processTableware[i].id == e.detail.id) {
        processTableware[i].over_num = e.detail.over_num;
        return;
      }
    }

    let processTableware2 = Object.assign({}, processTableware, processTableware.map(item => Object.assign({}, item, { over_num })));

    this.setData({
      processTableware: processTableware2
    })

  },

  //餐具消毒备注更新
  subRemaks(e){
    let { processTableware } = this.data;

    for (let i = 0; i < processTableware.length; i++) {
      if (processTableware[i].id == e.detail.id) {
        processTableware[i].sub_note = e.detail.sub_note;
        return;
      }
    }

    let processTableware2 = Object.assign({}, processTableware, processTableware.map(item => Object.assign({}, item, { sub_note })));

    this.setData({
      processTableware: processTableware2
    })
  },

  /**
   * @desc 提交
   */
  submitForm(){
    let { processEditTable, isSubmit} = this.data;
    let psEdTb = [];

    wx.request({
      url: setWork,
      method: 'POST',
      header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter,"Content-Type": "application/x-www-form-urlencoded" }, 
      data: { 
        tabel: JSON.stringify(this.data.processEditTable),   //粗加工类的数据
        report: JSON.stringify(this.data.processTableware)   //餐具消毒类的数据
        },
         
      success: (res) => {
        let { code,msg} = res.data;
        if (code == 200) {
          wx.showToast({
            title: '提交成功',
          })
          this.getRoughMachining();
          wx.request({
            url: workList,
            method: 'POST',
            header: { 'Cookie': 'PHPSESSID=' + this.data.isEnter, 'content-type': 'application/x-www-form-urlencoded' },
            data: { isEnter: this.data.isEnter },
            success: (res) => {
              let { code, mes, url, data } = res.data;
              if (code == 200) {
                this.setData({
                  isSubmit: mes.isSubmit,
                  job: mes.jobsName,
                  processEditTable: mes.data,
                  processTableware: mes.tableWare
                })
              }
            }
          })
        }else{
          console.log(res);
         wx.showToast({
           title: '请填写消毒数量',
         })
        }
      },
      fail:(res) => {
        wx.showModal({
          title: '提示',
          content: res,
          showCancel: false,
        })
      }
    })
  },

  /**
   * @desc 获取验证条件
   */
  getValidateOptions() {
    let { mobile, password } = this.data
    let data = [
      {
        value: mobile,
        strategies: [
          { strategy: 'isNotEmpty', errorMsg: '请填写餐具消毒的数量' },
        ],
      },
    ]

    return data
  },

  ...jobMixin,
  ...navMixin,
  ...inputMixin,
})
